﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using TeamDev.SDK;
using System.Xml.Serialization;
using System.Xml;

namespace TDB
{
  [Serializable]
  public class Configuration
  {
    private static string _configurationfilepath = string.Empty;
    public static Configuration Current { get; set; }

    public string DataBasePath { get; set; }
    public string ServerName { get; set; }
    public JournalingMode Journaling { get; set; }

    public List<string> DataBases { get; set; }

    static Configuration()
    {
      Configuration.Current = new Configuration();
      _configurationfilepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"TDB");
      _configurationfilepath = Path.Combine(_configurationfilepath, "config.data");
    }

    public Configuration()
    {
      ServerName = "TDB";
      DataBasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"TDB\DB");
      DataBases = new List<string>();
      Journaling = JournalingMode.Cached;
    }

    public static void Load()
    {
      if (File.Exists(_configurationfilepath))
      {
        XmlSerializer xmls = new XmlSerializer(typeof(Configuration));
        using (var file = new XmlTextReader(_configurationfilepath))
        {
          try
          {
            Configuration.Current = (xmls.Deserialize(file) as Configuration ?? Configuration.Current);
          }
          catch (Exception ex)
          {
            EventLogWriter.LogException(ex);
          }
        }
      }
    }

    public static void Save()
    {
      XmlSerializer xmls = new XmlSerializer(typeof(Configuration));
      if (!Directory.Exists(Path.GetDirectoryName(_configurationfilepath)))
        Directory.CreateDirectory(Path.GetDirectoryName(_configurationfilepath));

      using (var file = new XmlTextWriter(_configurationfilepath, Encoding.UTF8))
      {
        xmls.Serialize(file, Configuration.Current);
      }

    }
  }

  public enum JournalingMode
  {
    Off,
    Cached,
    Secure,
  }
}
